package com.gupaoedu.vip.netty.io.nio.buffer;

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @program:gupaoedu-vip-netty-io
 * @description:nio三件套之buffer
 * @author:Gongchao
 * @date:2020-04-27
 **/
public class BufferDemo {

    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("D://test.txt");
        //创建文件的操作管道
        FileChannel fileChannel = fileInputStream.getChannel();

        //分配一个10大小缓冲区，本质就是分配一个10大小的byte[]
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        output("初始化",byteBuffer);

        //读
        fileChannel.read(byteBuffer);
        output("调用read()",byteBuffer);

        //准备操作前，先锁定操作范围
        byteBuffer.flip();
        output("调用flip()",byteBuffer);

        //判断是否有可读数据
        while(byteBuffer.remaining() > 0) {
            byte b = byteBuffer.get();
//            System.out.println("读取到的数据为："+b);
        }
        output("调用get()",byteBuffer);

        //可以理解为解锁
        byteBuffer.clear();
        output("调用clear()",byteBuffer);

        //最后关闭管道
        fileChannel.close();
        //关闭流
        fileInputStream.close();

    }

    //把缓存区里面实时状态打印出来
    public static void output(String step,ByteBuffer byteBuffer) {
        System.out.println(step + ":");
        //容量，即数组大小
        System.out.println("capacity:"+byteBuffer.capacity()+",");
        //当前操作数据所在位置，可以理解为游标
        System.out.println("position:"+byteBuffer.position()+",");
        //锁定值，调用filp锁定数据操作访问，数据操作范围索引只能在position-limt之间
        System.out.println("limt:"+byteBuffer.limit());
        System.out.println();
    }
}
